<template>
	<view class="content" style="position:relative;">

		<view style="margin:10rpx; position: relative;">
			<!-- <view class="signImgBox">
				<image :src="src" v-if="src" mode="" class="signImgImg"></image>
			</view>
			<button type="default" class="button" @click="openSignBox">打开签字</button> -->

			<view class="signBox">
				<view class="signButtons">
					<view class="signBtn signCancle" style="color:#f00000" @click="signCancle">
						<view class="signtextrotate">取</view>
						<view class="signtextrotate">消</view>
					</view>
					<view class="signBtn signRewrite" style="color:#F0AD4E" @click="reSign">
						<view class="signtextrotate">重</view>
						<view class="signtextrotate">签</view>
					</view>
					<view class="signBtn signOk" style="color:#1AAD19" @click="signOk">
						<view class="signtextrotate">完</view>
						<view class="signtextrotate">成</view>
					</view>
				</view>
				<view class="signPaper">
					<canvas class="handWriting" disable-scroll="true" id="handWriting" canvas-id="handWriting"
						@touchstart="touchstart" @touchmove="touchmove">
					</canvas>
				</view>
				<view class="signTitle">
					<view class="signtextrotate">签</view>
					<view class="signtextrotate">名</view>
					<!-- <view class="signtextrotate">处</view> -->
				</view>
			</view>
		</view>
		<view :style="{'width':autoWidth+'px'}"
			style="height:550rpx;background-color: #ffffff; position:absolute;left:0 ;top:-9999px">
			<canvas canvas-id="autoWriting" id="autoWriting" style="width:100%;height:100%;"></canvas>
		</view>

		<!-- 图片转base64 -->
		<canvas id="photo" style="display: none;"></canvas>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				showSignBox: false,
				fixHeight: 0,
				autoWidth: 0,
				screenHeight: 0,
				drew: false,
				ctx: {},
				autoCtx: {},
				formData: {
					memberId: '',
					phone: '',
					companyId: '',
					//companyName: '',
					//companyCode: '',
					businessId: '',
					//businessName: '',
					tenantId: '',
					//signingService: '',
					signingServiceId: '',
					//releaseDate: '',
					//signContent: '',
					name: '',
					idCard: '',
					bankCardAccount: '',
					idCardZm: '',//身份证正面
					idCardFm: '',//身份证反面
					signImg: '', //签名图片
					signingFile: '',//签约文件
					resultStatus: false,//签约状态
					resultMessage: '',//签约错误消息
				},
				imgUrl: this.$requestApi.getImgUrl(),
			}
		},
		mounted() {
			uni.getSystemInfo({
				success: (res) => {
					this.fixHeight = 550 * res.windowWidth / 750;
					this.autoWidth = res.screenHeight;
				}
			});
		},
		props: {
			src: ''
		},
		onLoad(e) {
			if(!e.memberInfo){
				uni.showToast({title: "数据错误！",icon: "none",mask: true,});
				return;
			}
			this.formData = JSON.parse(decodeURIComponent(e.memberInfo));
			//打开签字版
			this.openSignBox();
		},
		methods: {
			signCancle() {
				this.src = '';
				// this.drew = false;
				// this.showSignBox = false;
				// this.ctx.draw();
				// this.autoCtx.draw();

				uni.reLaunch({
					url: '/signingPages/uplouIdCard?memberInfo=' + encodeURIComponent(JSON.stringify(this.formData))
				});
			},
			//打开签字
			openSignBox() {
				this.ctx = {};
				let ctx = uni.createCanvasContext("handWriting", this);
				ctx.setStrokeStyle("#000");
				ctx.setLineWidth(3);
				this.showSignBox = true;
				this.ctx = ctx;

				this.autoCtx = {};
				let autoCtx = uni.createCanvasContext("autoWriting", this);
				autoCtx.setFillStyle('#ffffff')
				autoCtx.fillRect(0, 0, this.autoWidth, this.fixHeight)
				autoCtx.setStrokeStyle("#000");
				autoCtx.setLineWidth(3);
				this.showSignBox = true;
				this.autoCtx = autoCtx;
			},
			reSign() {
				let ctx = this.ctx
				ctx.draw();
				this.src = '';
				this.drew = false;
				this.ctx = ctx;

				let autoCtx = this.autoCtx
				autoCtx.draw();
				this.autoCtx = autoCtx;
			},
			uploadSign(file) {
				//发送给后端的附加参数
				const formData = {
					biz: 'member/sign/' + this.formData.businessId,  
				};
				this.$requestApi.uploadImg({file, formData}, res=>{
					uni.hideLoading();
					if(res.success){
						this.formData.signImg = this.imgUrl + res.result;
						console.log("==用户签名==:",this.formData.signImg);
						//签名上传成功之后处理事件
						uni.showLoading({title: '请稍后...',mask: true})
						this.$requestApi.editMember({id: this.formData.memberId,signImg: this.formData.signImg}).then(res => {
							uni.hideLoading();
							this.formData.resultStatus = res.success;
							// this.formData.signingFile = res.result;
							this.formData.resultMessage = res.message;
							uni.reLaunch({
								url: '/signingPages/resultPage?memberInfo=' + encodeURIComponent(JSON.stringify(this.formData))
							});
						});
						
					}else{
						uni.showToast({title: res.message,icon: "none",mask: true,});
						return;
					}
				});
			},
			//图片转base64
			urlTobase64(url){
				return new Promise((resolve, reject) => {
					uni.getFileSystemManager().readFile({
						filePath: url, //选择图片返回的相对路径
						encoding: 'base64', //编码格式
						success: res => { //成功的回调
							console.log(res);
							let base64 = 'data:image/png;base64,' + res.data //不加上这串字符，在页面无法显示的哦
							resolve(base64);
						},fail: (err) => {
							console.log("图片转换失败");
							reject(err); 
						}
					})
				})
			},
			signOk() {
				if (this.drew) {
					uni.showLoading({
						title: '签约中...',
						mask: true,
					})
					uni.canvasToTempFilePath({
						canvasId: 'autoWriting',
						fileType: 'png',
						destWidth: 180,
						destHeight: 120,
						success: async (res) => {
							// 在H5平台下，tempFilePath 为 base64
							// console.log("=====:",res.tempFilePath)
							if(res.tempFilePath.indexOf('data:image/png;base64,') != -1){
								this.formData.signImg = res.tempFilePath;
							}else{
								// this.formData.signImg = result;
								//图片转base64
								// await this.urlTobase64(res.tempFilePath).then((result) => {
								// 	this.formData.signImg = result;
								// });
								//图片上传
								await this.uploadSign(res.tempFilePath);
							}
						},
						fail: (res) => {
							console.log("res", res); //errMsg:"canvasToTempFilePath: fail canvas is empty"
						},
					}, this)
					// this.drew = false;
					// this.ctx.draw();
					// this.autoCtx.draw();
					uni.hideLoading();
				} else {
					this.src = '';
					uni.showToast({title: "请先完成签名！",icon: "none",mask: true,});
					return;
				}
				// this.showSignBox = false;
			},
			touchstart(e) {
				this.drew = true;
				this.ctx.moveTo(e.touches[0].x, e.touches[0].y);
				let autoPoint = this.transformAutoDrawPoint(e.touches[0].x, e.touches[0].y)
				this.autoCtx.moveTo(autoPoint.x, autoPoint.y);
			},
			touchmove(e) {
				var x = e.touches[0].x;
				var y = e.touches[0].y;
				this.ctx.setLineWidth(3);
				this.ctx.lineTo(x, y);
				this.ctx.stroke();
				this.ctx.setLineCap('round');
				this.ctx.draw(true);
				this.ctx.moveTo(x, y);

				let autoPoint = this.transformAutoDrawPoint(e.touches[0].x, e.touches[0].y)
				this.autoCtx.setLineWidth(3);
				this.autoCtx.lineTo(autoPoint.x, autoPoint.y);
				this.autoCtx.stroke();
				this.autoCtx.setLineCap('round');
				this.autoCtx.draw(true);
				this.autoCtx.moveTo(autoPoint.x, autoPoint.y);
			},
			transformAutoDrawPoint(x, y) {
				let autoPoint = {};
				autoPoint.x = y;
				autoPoint.y = -x + this.fixHeight;
				return autoPoint;
			}
		}
	}
</script>

<style>
	.signImgBox {
		border: 1rpx dashed #ededed;
		height: 300rpx;
		margin: 20rpx 0rpx 20rpx 0rpx;
		width: 730rpx;
		background: #fdfdfd;
	}

	.signImgImg {
		width: 730rpx;
		height: 300rpx;
	}

	.sign-btn {
		margin: 0 20rpx;
	}

	.signBox {
		width: 100%;
		height: 100%;
		background-color: #ffffff;
		position: fixed;
		left: 0;
		top: 0;
		display: flex;
		z-index: 9999;
	}

	.signButtons {
		width: 100rpx;
		background-color: #ededed;
		height: 100%;
		border-right: 1px solid #dedede;
		display: flex;
		flex-direction: column;
		justify-content: center;
		text-align: center;
	}

	.signPaper {
		width: 550rpx;
		background: #ffffff;
		height: 100%;
	}

	.signTitle {
		background-color: #ffffff;
		border-left: 1px solid #dedede;
		width: 100rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		text-align: center;
	}

	.signtextrotate {
		transform: rotate(90deg);
	}

	.signBtn {
		width: 100%;
		height: 100%;
		text-align: center;
		display: flex;
		flex-direction: column;
		justify-content: center;
		border-bottom: 1px solid #dedede;
	}

	.handWriting {
		width: 100%;
		height: 100%;
	}
</style>
